package com.road.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.road.common.utils.IPUtils;
import com.road.common.utils.JsonMapper;
import com.road.model.entity.SysLog;
import com.road.service.LogService;
import com.road.shiro.ShiroUser;

import eu.bitwalker.useragentutils.UserAgent;


/**
 * @Description :
 * @FileName: LogInterceptor.java
 * @Author :WeiHui.Zhang
 * @Data : 2016年3月16日 上午10:28:02
 * @Version:V1.00
*/
public class LogInterceptor implements HandlerInterceptor{
	
	
	private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);

	
	@Autowired
	private LogService logService;

	private Long beginTime;// 1、开始时间
	private Long endTime;// 2、结束时间
	
	
	/**
	 * 执行controller之后，但是在filter返回给客户端之前调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		endTime = System.currentTimeMillis();
		String requestRri = request.getRequestURI();
		String uriPrefix = request.getContextPath();
		String operationCode=StringUtils.substringAfter(requestRri,uriPrefix);	//操作编码
		
		String requestParam=(new JsonMapper()).toJson(request.getParameterMap());	//请求参数
		
		//如果是GET请求，请求编码包含create，update(添加修改页)不记录日志
		if(request.getMethod().equals("GET")){
			if(operationCode.contains("create")||operationCode.contains("update")){
				return;
			}
		}
		Long executeTime=endTime-beginTime;
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); 
		String os=userAgent.getOperatingSystem().getName();	//获取客户端操作系统
		String browser=userAgent.getBrowser().getName();	//获取客户端浏览器
		ShiroUser shiroUser = ShiroUser.getCurrentShiroUser();
		
		SysLog log=new SysLog();
		log.setOs(os);
		log.setBrowser(browser);
		log.setClientIp(IPUtils.getIpAddress(request));
		log.setOptUri(operationCode);
		log.setExecuteTime(Integer.valueOf(executeTime.toString()));
		if(shiroUser != null){
			log.setUserId(shiroUser.getId());
			log.setLoginName(shiroUser.getLoginName());
			log.setRoleName("");
		}
		log.setCreateTime(new Date());
		//log.setDescription(LogCodeUtil.matchingOperationCode(operationCode));
		log.setRequestParam(requestParam);
		
		//放到一公共变量里，定时提交
		logService.save(log);
	}

	/**
	 * 执行完controller的逻辑，在controller里的 return modelandView之前调用，可以更改ModelAndView里的值
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}

	/**
	 * 进入拦截器，在controller之前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		LOGGER.debug("本次访问记录日志");
		beginTime = System.currentTimeMillis();//计时
		return true;
	}

}
